import { func } from "prop-types";
import React, { Component } from "react";

// 1.0 导入react-router-dom
import {
  BrowserRouter as Router,
  Route,
  Link,
  Redirect,
} from "react-router-dom";
// import { HashRouter as Router, Route, Link } from "react-router-dom";
// 当做根组件
class RouterDemo extends Component {
  state = {};
  render() {
    return (
      <div
        style={{
          width: "600px",
          height: "300px",
          margin: "20px auto",
          backgroundColor: "pink",
          padding: "5px",
        }}
      >
        {/* 2.0 使用Router包裹住接下来所有的路由组件 */}
        <Router>
          {/* 3.0 做出一点点击按钮用来触发路由的跳转 */}
          <Link to="/home" style={{ marginRight: "10px" }}>
            跳转到Home组件
          </Link>
          <Link to="/login">跳转到Login组件</Link>
          {/* 4.0 定义路由规则和此规则展示的组件 */}
          {/* 路由规则的中的path与浏览器中的url路径pathname是一个模糊匹配的过程，如果加上exact 就可以将路由规则变为精确匹配 */}
          <Route path="/" exact component={HomeRoute1}></Route>

          {/* 使用Redirect组件进行路由重定向功能 */}
          {/* <Route
            path="/"
            render={() => {
              return <Redirect to="/login"></Redirect>;
            }}
          ></Route> */}

          <Route path="/home" component={HomeRoute1}></Route>
          <Route path="/login" component={LoginRoute}></Route>
        </Router>
      </div>
    );
  }
}

export default RouterDemo;

class HomeRoute1 extends Component {
  state = {};
  render() {
    return (
      <div
        style={{
          margin: "20px auto",
          backgroundColor: "greenyellow",
          padding: "5px",
        }}
      >
        Home Route <br />
        <Router>
          <Link to="/home/user" component={User}>
            跳转到User
          </Link>
          <Link to="/home/role" component={Role}>
            跳转到Role
          </Link>
        </Router>
        <button
          onClick={() => {
            this.props.history.go(-1);
          }}
        >
          回退一页
        </button>
      </div>
    );
  }
}

class LoginRoute extends Component {
  state = {};
  render() {
    return (
      <div
        style={{
          margin: "20px auto",
          backgroundColor: "#ccc",
          padding: "5px",
        }}
      >
        Login Route
        <br />
        <button
          onClick={() => {
            /*通过编程式导航跳转到首页*/ this.props.history.push("/home");
          }}
        >
          登录
        </button>
      </div>
    );
  }
}

function User() {
  return <div>User组件</div>;
}

function Role() {
  return <div>Role组件</div>;
}
